<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\HouseLease;
use Illuminate\Http\Request;

/**
 * Class HouseLeaseController
 * @package App\Http\Controllers\Admin
 * 房源出租控制器
 */

class HouseLeaseController extends Controller
{
    public function index(Request $request)
    {
        $house_type = $request->get('house_type');
        $where = [];

        //添加可选参数
        if ($house_type) {
            $where[] = ['type', '=', $house_type];
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;


        //发布时间倒序
        $data = HouseLease::query()->with('community:community_id,community_name')->select('id', 'user_id', 'title', 'money', 'image', 'more_option', 'describe', 'type', 'community_id', 'area', 'house_type', 'direction', 'created_at')->where($where)->orderByDesc('created_at')->offset($offset)->limit($limit)->get()->each(function ($item) {
            $item['more_option'] = json_decode($item['more_option'], true);
            return $item;
        });
        $response['data'] = $data;
        $response['count'] = HouseLease::query()->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);
        return $this->success($response, '请求成功');
    }

    public function show($id)
    {
        $data = HouseLease::query()->with('community:community_id,community_address,city,community_name')->where('id', $id)->first()->toArray();
        if ($data) {
            $data['images'] = array_filter(explode(',', $data['images']), function ($item){
                return $item && true;
            });
            $data['more_option'] = json_decode($data['more_option'], true);
        }

        return $this->success($data);
    }
}
